/*jslint browser: true, devel: true*/
/* global $ window EChat initChatSdk */
function _typeof (obj) {
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function _typeof (obj) {
      return typeof obj;
    };
  } else {
    _typeof = function _typeof (obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }
  return _typeof(obj);
}

// 远程桌面
var chatSDK = window.chatSDK || {};
var chatUiKit = window.chatUiKit || {};

/**
 * 页面加载完成，初始化聊天SDK
 */
function initChatSdk () {
  var options = {
    debug: true,
    debugAll: false,
    enableAutoLogin: AgentApi.checkAuth("Multimedia_Auto_login") || (localStorage.getItem("chat_enableAutoLogin") == "true" ? true : false),
    enableImAck: false
  };
  chatSDK = new EChat.chat(window.CONFIG.agentProxyServer, options);
  if (window.CONFIG.platform == "genesys" && Agent.getCurrentAgent().placeId == '') {
    globalUiKit.alert('', '座席工号异常，Place为空')
  }
  chatSDK.setCurrentAgent(Agent.getCurrentAgent());
  chatSDK.connectToAgentProxy();
  chatSDK.init(AppEventHandler);
  window.globalUiKit.vm.$emit('chatChannel', true);
}
function initChatUiKit () {
  chatUiKit = new ChatUiKit();
}

/**
 * Chat UI工具库
 * @constructor
 */
var ChatUiKit = function ChatUiKit () {
  // 变量替换
  var self = this;

  this.getServerTime = function () {
    var timestamp = new Date().getTime() - Constants.diffTimeLocalAndServer;
    return new Date(timestamp).Format("yyyy-MM-dd HH:mm:ss").substring(0, 19)
  };
  //清理定时器
  this.clearIntervalSession = function (sessionId) {
    if (intervalSessionMap[sessionId]) {
      clearInterval(intervalSessionMap[sessionId].interval);
      delete intervalSessionMap[sessionId];
    }
  },
    //清理座席定时器
    this.clearIntervalAgentSession = function (sessionId) {
      if (intervalAgentSessionMap[sessionId]) {
        clearInterval(intervalAgentSessionMap[sessionId].interval);
        delete intervalAgentSessionMap[sessionId];
      }
    }
  // 恢复保持取回
  this.resetHoldorRetrieve = function (sessionId) {
    var user = Model.people.get_by_sid(sessionId);
    if (!user) {
      return;
    }
    if (holdFlagMap[sessionId]) {
      chatUiKit.clearIntervalSession(sessionId);
      chatUiKit.clearIntervalAgentSession(sessionId);
    } else {
      if (user.lastMsgSender == 'client') {
        chatUiKit.clearIntervalSession(sessionId);
        chatUiKit.clearIntervalAgentSession(sessionId);
        AppEventHandler.intervalAgentClock(sessionId);
      } else {
        chatUiKit.clearIntervalAgentSession(sessionId);
        chatUiKit.clearIntervalSession(sessionId);
        AppEventHandler.intervalClock(sessionId);
      }
    }
  }
  this.resetHoldorRetrieve_Reconnect = function (sessionId) {
    var user = Model.people.get_by_sid(sessionId);
    if (!user) {
      return;
    }
    if (holdFlagMap[sessionId]) {
      chatUiKit.clearIntervalSession(sessionId);
      chatUiKit.clearIntervalAgentSession(sessionId);
    } else {
      if (user.lastMsgSender == 'client') {
        chatUiKit.clearIntervalSession(sessionId);
        AppEventHandler.intervalAgentClock(sessionId);
      } else {
        chatUiKit.clearIntervalAgentSession(sessionId);
        AppEventHandler.intervalClock(sessionId);
      }
    }
  }
  /**
   * 座席切换用户(第一进线也统一走这个方法)
   * @param obj
   */
  this.changeRecordList = function (obj) {
    // 1.获取当前页签显示的用户
    var curUser = Model.people.get_user();
    if (curUser && curUser.sid === obj.sessionId) {
      return;
    }
    if (curUser && curUser.chatType !== 'call') {
      Model.people.set_inputContent($('.chat-mess.' + curUser.sid).val(), curUser.sid);// 不是当前显示的用户，保存当前用户的输入框内容
      window.globalUiKit.vm.$emit("inputValueChange", '');//切换时候隐藏当前会话的输入联想
    }
    // 切换当前用户
    Model.people.change_user(obj.sessionId);
    // 切换客户资料
    curUser = Model.people.get_user();
    if (obj.channelType === 'call') {
      $('#mediaContent').removeClass('fade active in')
      $('#phoneContent').addClass('fade active in')
      $('.voiceContentActive').removeClass('voiceContentActive');
      $('.voicecontent[name="' + obj.sessionId + '"]').addClass('voiceContentActive');
    } else {
      chatUiKit.switchChatrecord(obj);
      $('#mediaContent').addClass('fade active in')
      $('#phoneContent').removeClass('fade active in')
      // 未读消息数清零
      Model.people.setNoReadMsgNum(obj.sessionId, 0);
      // 3.4 聊天窗口切换
      $('.chatContentActive').removeClass('chatContentActive');
      $('.chatcontent[name="' + obj.sessionId + '"]').addClass('chatContentActive');
      // 3.6 根据会话的状态来显示按钮
      globalUiKit.vm.$emit(globalUiKit.globalEvent.EVENT_CHAT_STATUES_CHANGE, curUser)
      // 3.9 聊天显示区滚动轴置底
      $(".chat-interaction-scroll .el-scrollbar__wrap")[0].scrollTop = $(".chat-interaction-scroll .el-scrollbar__wrap")[0].scrollHeight;
      if (AgentApi.checkAuth('IntelligentAssistant') && Constants.chatDoneStatus.indexOf(curUser.chatState) == -1 && curUser.lastMsgSender == 'client' && curUser.lastMsgType == "text" && curUser.lastMsg != "") {
        ThirdApi.robotAPI(curUser.lastMsg, curUser.sid, '', '', ThirdApi.robotSuccessHandler);
      }
    }
  };

  // 切换客户页签判断是否有未读消息，若有给客户端发送已读消息标识
  this.switchChatrecord = function (item) {
    var messageText = new Object();
    messageText.mediaid = ''
    messageText.msgtype = 'text'
    messageText.touser = item.uid || ''
    messageText.fromuser = Agent.getCurrentAgent().agentId || ''
    messageText.channeltype = Agent.getCurrentAgent().chatType || ''
    messageText.interactionid = item.sessionId || ''
    messageText.chatmode = 'normal'
    messageText.genderMap = Agent.getCurrentAgent().genderMap || ''
    messageText.nickname = chatUiKit.getAgentNickNamePrefixByAppid(item.sessionId) + Agent.getCurrentAgent().nickName
    messageText.userdata = {
      'totalreaded': true
    }
    messageText.content = ''
    if (item.hasOwnProperty('noReadMsgNum')) {
      if (item.noReadMsgNum) {
        chatSDK.sendChatMsg(item.sessionId, messageText);
      }
    } else {
      console.log('切换页签没有未读消息')
    }
  }

  // 静默座席切换用户(第一进线也统一走这个方法)
  this.changeUserSilent = function (sessionId) {
    Model.people.change_user(sessionId);
    var curUser = Model.people.get_user();
    globalUiKit.vm.$emit(globalUiKit.globalEvent.EVENT_CHAT_STATUES_CHANGE, curUser)
  };
  // 初始化聊天窗口
  var initChatDiv = function (sessionId) {
    if ($('.chatcontent[name="' + sessionId + '"]').length == 0) {
      let msgtext = i18n.promptMessage.chatTips.currentSession;
      let sessionHtml = '<div style="text-align:center; display: none">' + msgtext + 'ID："' + sessionId + '"</div>';
      var chatContentDiv = '<div class="chatcontent photoCon" name="' + sessionId + '" >' + sessionHtml + chatUiKit.getChatReminderHtml(sessionId) + '</div>';
      $('.chat-interaction').append(chatContentDiv);
    }
  };
  this.getChatReminderHtml = function (sessionId) {
    var chatreminder = '<div class="reminder reminderShow chat-robot" id="chat-robot" name="' + sessionId + '" tabindex="3">\n' +
      '    <div class="contentRobot">\n' +
      '<p class="contentRobotHeader">知识随行</p>' +
      '      <div class="url">\n' +
      '        <p class="pull-left col-sm-12 robotResponse"></p>\n' +
      '      </div>\n' +
      '      <div class="chatRobotbutton">\n' +
      '        <span class="redirectsendbtn" onclick=chatUiKit.redirectSendBtnClick("' + sessionId + '")>发送</span>\n' +
      '        <span class="editsendbtn" onclick=chatUiKit.editSendBtnClick("' + sessionId + '")>编辑</span>\n' +
      '        <span class="editsendClose" onclick=chatUiKit.editSendCloseClick("' + sessionId + '")>关闭</span>\n' +
      '      </div>\n' +
      '    </div>\n' +
      '  </div>';
    return chatreminder;
  }

  /**
   * 缓存客户信息，初始化聊天窗口
   * @param sessionId 会话ID
   * @param userId 进线号
   * @param channelType 渠道类型
   * @param extension 分机号
   * @param chatState 会话类型
   * @param bizType 业务类型
   */
  this.joinChatList = function (sessionId, userId, userName, channelInfo, channelType, extension, chatState, bizType, requestData, chatMode, srcAgentId) {
    // 1.创建用户
    if (Settings.debugAll) console.log(new Date() + ", log info [ new user join ]");
    phoneUiKit.checkExistSession(sessionId);
    if (!AgentApi.checkAuth(Constants.agentType.SilentChatAgent)) {
      // 2.初始化聊天面板
      initChatDiv(sessionId);
    }
    Model.people.on_begin_chat(sessionId, userId, channelInfo, channelType, extension, chatState, bizType, '', requestData, '', '', userName);
    if (requestData) {
      if (requestData.language != '') {
        Model.people.get_by_sid(sessionId).language = Utils.transLang2Standard(requestData.language);
      }
    }
  };
  this.appendSessionTime = function appendSessionTime (divId, item) {
    if ($(divId).find('.user').length > 0) {
      var lastSession = $($(divId).find('.user')[0]).attr('sessionId')
      if (item.sessionid != lastSession) {
        var lastCreateTime = $($(divId).find('.user')[0]).attr('createTime');
        if (lastCreateTime) {
          var showLastSessionTime = lastCreateTime.split(' ')[0].replace('-', '年').replace('-', '月') + '日 ' + lastCreateTime.split(' ')[1]
          $(divId).prepend('<div style="text-align: center;margin:5px;"><span style="background: #e3e5e7;padding: 2px 10px;border-radius: 5px;">' + showLastSessionTime + '</span></div>');
        }
      }
    }
  };
  /**
   * 展示当前客户历史聊天记录
   */
  this.showUserHistoryContent = function (callback) {
    if (!Model.people.get_user() || Model.people.get_user().isCheckMoreFlag == false) {
      return;
    }
    let messageJson = {}
    var userId = Model.people.get_user().uid;
    var sessionId = Model.people.get_user().sid;
    var tenantId = Agent.getCurrentAgent().tenantId;
    var divId = $('.chatcontent[name=' + sessionId + ']');
    Model.people.get_user().currentPage = Model.people.get_user().currentPage || 1;
    var page = Model.people.get_user().currentPage;
    var url = window.CONFIG.restIp + '/v1/history/customerchat/' + tenantId + '?tenantId=' + tenantId + '&userid=' + userId + '&excludedSessionId=' + sessionId + '&page=' + page + '&pagesize=10&sort=1';
    console.log(new Date() + "获取转人工历史聊天记录：" + url);
    CommonApi.httpGetRequest(url, function (data) {
      console.log('获取历史消息', JSON.stringify(data));
      Model.people.get_user().currentPage = Model.people.get_user().currentPage + 1;
      if (data.retCode == 1) {
        var chatContentList = data.data.chatHistories;
        if (chatContentList.length == 0) {
          chatUiKit.appendSessionTime(divId, {});
          Model.people.get_user().isCheckMoreFlag = false;
        }
        if (chatContentList && chatContentList.length > 0) {
          Model.people.get_user().isCheckMoreFlag = true;
          $.each(chatContentList, function (i, item) {
            try {
              var mediaType = item.msgtype;
              if (Settings.debugAll) console.log("聊天历史记录内容：" + chatContentList[i].content);
              var message = item.content;
              var mediaContent = item.content;
              var createTime = item.createtime;
              var fileName = item.filename || ''
              if (mediaType == "voice" || mediaType == 'jpg' || mediaType == 'png' || mediaType == 'jpeg' || mediaType == 'gif' || mediaType == 'bmp' || mediaType == 'doc' || mediaType == 'docx' || mediaType == 'mp3' || mediaType == 'avi' || mediaType == 'mp4' || mediaType == 'wmv' || mediaType == 'ppt' || mediaType == 'pptx' || mediaType == 'xlsx' || mediaType == 'xls' || mediaType == 'pdf') {
                message = chatContentList[i].content;
              } else if (mediaType == 'transaction') {
                var m = JSON.parse(chatContentList[i].content);
                mediaContent = m.resource;
              } else if (mediaType == 'link') {
                var linkobj = JSON.parse(chatContentList[i].content);
                mediaContent = linkobj.resource
                fileName = linkobj.desc
              } else if (mediaType == 'joinconference') {
                return;
              }

              if (item.content == '\u0004EventRobot2Silent\u0004' || item.content == '\u0004EventSilentAgentNotFound\u0004' || item.content == '\u0004EventSilentAgentClientEnd\u0004') {
                item.content = '';
              }
              var fromuser = '';
              var agentId = Agent.getCurrentAgent().agentId;
              chatUiKit.appendSessionTime(divId, item);
              // 从座席发出的消息（右边显示）
              if (item.fromuser === agentId) {
                messageJson.parentEle = divId
                messageJson.sessionId = item.sessionid
                messageJson.message = mediaContent
                messageJson.mediatype = item.msgtype
                messageJson.fileName = fileName
                messageJson.fromUser = item.nickname || item.fromuser
                messageJson.createTime = createTime
                messageJson.setHistory = ''
                messageJson.uuid = ''
                messageJson.sort = true
                messageJson.publisher = item.publisher
                self.appendChatMessageFromMe(messageJson, false, true)
              }
              // 从座席发出的消息（右边显示）,机器人发的
              else if ((item.fromuser === null && item.touser !== agentId) || item.fromuser == "robot") {
                messageJson.parentEle = divId
                messageJson.sessionId = item.sessionid
                messageJson.message = mediaContent
                messageJson.mediatype = item.msgtype
                messageJson.fileName = fileName
                messageJson.fromUser = i18n.promptMessage.chatTips.robot
                messageJson.createTime = createTime
                messageJson.setHistory = ''
                messageJson.uuid = ''
                messageJson.sort = true
                messageJson.publisher = item.publisher
                self.appendChatMessageFromMe(messageJson, false, true)
              }
              // 发给座席的消息（左边显示）
              else {
                messageJson.parentEle = divId
                messageJson.sessionId = item.sessionid
                messageJson.message = mediaContent
                messageJson.mediatype = item.msgtype
                messageJson.toUser = item.nickname || item.fromuser
                messageJson.createTime = createTime
                messageJson.setHistory = ''
                messageJson.highLight = ''
                messageJson.sid = ''
                messageJson.fileName = fileName
                messageJson.sort = true
                messageJson.publisher = item.publisher
                self.appendChatMessageToMe(messageJson, false, false, true)
              }
            } catch (e) {
              console.log(e);
            }
          });
        }
        callback && callback();
      }
    })
  };

  /**
   * 展示历史聊天记录
   */
  this.showHistoryContent = function (sessionId, welcome, callback) {
    if (!sessionId) {
      return;
    }
    let messageJson = {}
    var divId = $('.chatcontent[name=' + sessionId + ']');
    var url = window.CONFIG.restIp + '/v1/history/chat/' + Agent.getCurrentAgent().tenantId + '/' + sessionId + '?sort=1';
    if (Settings.debugAll) {
      console.log(new Date() + "获取转人工历史聊天记录请求：" + url);
    }
    CommonApi.httpGetRequest(url,
      function (data) {
        if (Settings.debugAll) console.log('获取历史消息响应：' + data);
        if (data.retCode = 200) {
          var chatContentList = data.data.chatContentList;
          var firstMessageTomeFlag = false
          if (chatContentList != null) {
            $.each(chatContentList, function (i, item) {
              try {
                var mediaType = item.msgtype;
                if (Settings.debugAll) console.log("聊天历史记录内容：" + chatContentList[i].content);
                var message = item.content;
                var mediaContent = item.content;
                var createTime = item.createtime;
                var fileName = item.filename || ''
                // 标识收到的第一条消息
                if (i == (chatContentList.length - 1)) {
                  console.log('Model.people.get_by_sid(data.data.sessionid)', Model.people.get_by_sid(data.data.sessionid))
                  firstMessageTomeFlag = true
                  Model.people.get_by_sid(data.data.sessionid).messageTimeObj = {
                    moreMessageTime: createTime || '',
                    realTimes: createTime || '',
                  }
                }

                if (mediaType == "voice" || mediaType == 'jpg' || mediaType == 'png' || mediaType == 'jpeg' || mediaType == 'gif' || mediaType == 'bmp' || mediaType == 'doc' || mediaType == 'docx' || mediaType == 'mp3' || mediaType == 'avi' || mediaType == 'mp4' || mediaType == 'wmv' || mediaType == 'ppt' || mediaType == 'pptx' || mediaType == 'xlsx' || mediaType == 'xls' || mediaType == 'pdf') {
                  message = chatContentList[i].content;
                } else if (mediaType == 'transaction') {
                  var m = JSON.parse(chatContentList[i].content);
                  mediaContent = m.resource;
                } else if (mediaType == 'link') {
                  var linkobj = JSON.parse(chatContentList[i].content);
                  mediaContent = linkobj.resource
                  fileName = linkobj.desc
                } else if (mediaType == 'joinconference') {
                  return;
                }

                if (item.content == '\u0004EventRobot2Silent\u0004' || item.content == '\u0004EventSilentAgentNotFound\u0004' || item.content == '\u0004EventSilentAgentClientEnd\u0004') {
                  item.content = '';
                }
                var fromuser = '';
                var agentId = Agent.getCurrentAgent().agentId;
                // 从座席发出的消息（右边显示）
                if (item.fromuser === agentId) {
                  messageJson.parentEle = divId
                  messageJson.sessionId = sessionId
                  messageJson.message = mediaContent
                  messageJson.mediatype = item.msgtype
                  messageJson.fileName = fileName
                  messageJson.fromUser = item.nickname || item.fromuser
                  messageJson.createTime = createTime
                  messageJson.setHistory = ''
                  messageJson.uuid = ''
                  messageJson.sort = true
                  messageJson.publisher = item.publisher
                  self.appendChatMessageFromMe(messageJson)
                }
                // 从座席发出的消息（右边显示）,机器人发的
                else if ((item.fromuser === null && item.touser !== agentId) || item.fromuser == "robot") {
                  messageJson.parentEle = divId
                  messageJson.sessionId = sessionId
                  messageJson.message = mediaContent
                  messageJson.mediatype = item.msgtype
                  messageJson.fileName = fileName
                  messageJson.fromUser = i18n.promptMessage.chatTips.robot
                  messageJson.createTime = createTime
                  messageJson.setHistory = ''
                  messageJson.uuid = ''
                  messageJson.sort = true
                  messageJson.publisher = item.publisher
                  self.appendChatMessageFromMe(messageJson)
                }
                // 发给座席的消息（左边显示）
                else {
                  messageJson.parentEle = divId
                  messageJson.sessionId = sessionId
                  messageJson.message = mediaContent
                  messageJson.mediatype = item.msgtype
                  messageJson.toUser = item.nickname || item.fromuser
                  messageJson.createTime = createTime
                  messageJson.setHistory = ''
                  messageJson.highLight = ''
                  messageJson.sid = ''
                  messageJson.fileName = fileName
                  messageJson.sort = true
                  messageJson.publisher = item.publisher
                  self.appendChatMessageToMe(messageJson, false, firstMessageTomeFlag)
                }
              } catch (e) {
                console.log(e)
              }
            });
          }
          callback && callback();
        }
        if (welcome) {
          chatUiKit.sendWelcome(sessionId);
        }
      },
      function (data) {
        if (welcome) {
          chatUiKit.sendWelcome(sessionId);
        }
      })
  };
  this.sendWelcome = function (sessionId) {
    let messageJson = {}
    var curUser = Model.people.get_by_sid(sessionId);
    if (!curUser) {
      return;
    }
    var divId = $('.chatcontent[name=' + sessionId + ']');
    var agentNickName = Agent.getCurrentAgent().nickName;
    var msg = CommonParameters.getTenantHintByTypeEng('ChatEstablishWelcome').replace('<AgentNickName>', chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + agentNickName) || i18n.promptMessage.chatTips.agentAnswer1 + agentNickName + i18n.promptMessage.chatTips.agentAnswer2;
    if (curUser.chatState == 'transfer') {
      msg = CommonParameters.getTenantHintByTypeEng('TransferSuccessWelcomeTips').replace('<AgentNickName>', chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + agentNickName) || i18n.promptMessage.chatTips.agentAnswer1 + agentNickName + i18n.promptMessage.chatTips.agentAnswer2;
    } else if (curUser.chatState == 'conference') {
      msg = CommonParameters.getTenantHintByTypeEng('ConfSucessWelcomeTips').replace('<AgentNickName>', chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + agentNickName) || i18n.promptMessage.chatTips.agentAnswer1 + agentNickName + i18n.promptMessage.chatTips.agentAnswer2;
    }
    var timeHtml = '<div style="text-align:center;">' + i18n.promptMessage.chatTips.SessionEstablishedSuccessfully + '"' + chatUiKit.getServerTime() + '"</div>';
    $('.chat-robot[name=' + sessionId + ']').before(timeHtml)
    if (Settings.chat.welcome) {
      var messageText = {};
      messageText.mediaid = '';
      messageText.msgtype = 'systemmsg';
      messageText.publisher = 'agentsystem';
      messageText.content = msg;
      messageText.filename = '';
      messageText.touser = curUser.uid;
      messageText.fromuser = Agent.getCurrentAgent().agentId;
      messageText.channeltype = curUser.chatType;
      messageText.interactionid = sessionId;
      messageText.chatmode = 'normal';
      messageText.genderMap = Agent.getCurrentAgent().genderMap;
      messageText.nickname = chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + Agent.getCurrentAgent().nickName;
      var chatState = curUser.chatState;
      if (chatState !== 'monitor' && chatState !== 'coach') { //监听和咨询不用发欢迎语给座席A和客户
        chatSDK.sendChatMsg(sessionId, messageText);
      }
      if (chatState !== 'monitor') { //监听不发欢迎语也不显示欢迎语
        messageJson.parentEle = divId
        messageJson.sessionId = sessionId
        messageJson.message = msg
        messageJson.mediatype = 'systemmsg'
        messageJson.fileName = ''
        messageJson.fromUser = Agent.getCurrentAgent().nickName
        messageJson.publisher = 'agentsystem'
        chatUiKit.appendChatMessageFromMe(messageJson)
      }
    }
  },

    // 发送输入开始
    this.sendTextInputStatus = function (eventInputStatus) {
      if (AgentApi.checkAuth(Constants.agentType.SilentChatAgent)) {
        return;
      }
      let msg = {
        msgtype: eventInputStatus,
        content: ''
      }
      chatUiKit.sendCurrentUsrMsg(msg)
    }

  /** --orderuse
   * 座席自己发给别人的消息，右边显示（发给座席或客户） sessionId是该消息所属的sessionId,注意，目前历史消息的sessionId会和当前不一致。    historyFlag 交互历史详情中显示聊天内容标识
   */
  this.appendChatMessageFromMe = function (obj, historyFlag, viewMoreMessage) {
    let parentEle = obj.parentEle || ''
    let sessionId = obj.sessionId || ''
    let message = obj.message || ''
    let mediatype = obj.mediatype || ''
    window.currentMediaType = mediatype;
    let fileName = obj.fileName || ''
    let fromUser = obj.fromUser || ''
    let createTime = obj.createTime || chatUiKit.getServerTime()
    let setHistory = obj.setHistory || ''
    let uuid = obj.uuid || ''
    let sort = obj.sort || ''
    let publisher = obj.publisher || '';
    // 判断消息是否为空
    if (!message) {
      return;
    }
    this.setLastMsg(obj);
    message = chatUiKit.resolveTextToEmotion(message);
    // var avatar = Agent.getCurrentAgent().avatar || Constants.basicConfig.agentDefaultAvatar || './pro/interact/assets/multimedia/images/agentHead.png';
    fileName = fileName || message;
    var retractTime = chatUiKit.getServerTime().replace(/-/g, '/');
    if (publisher == 'system' || mediatype === "systemmsg") {
      fromUser = i18n.promptMessage.chatTips.System;
    }
    // 1.各种类型message封装   交易
    if (mediatype == "text" || mediatype == "systemmsg" || mediatype == 'transferAgent' || mediatype == 'transaction' || mediatype == 'satisfaction') {
      if (message && message.indexOf("pro/interact/multimedia/chat/img/face/") < 0) {
        /*                message = message.replace(/</g, '&lt;');
                                message = message.replace(/>/g, '&gt;');
                                var regx = /<[^>]*>|<\/[^>]*>/gm;
                                message = message.replace(regx, '');
                                message = message.replace(/\n/g, '<br/>');*/
        if (ThirdApi.isHtml(message)) {
          var message1 = "";
          if (ThirdApi.isJSON(message)) {
            message = JSON.parse(message);
            if (message.description) {
              message1 += '<div style="float: left;width: 60%"><p>' + message.description + '</p></div>';
            }
            message1 += '<div class="url" style="float: left;width: 30%">' + message.content + '</div>';
            message = message1;
          } else {
            /*            message = message.replace(/</g, '&lt;');
                        message = message.replace(/>/g, '&gt;');
                        var regx = /<[^>]*>|<\/[^>]*>/gm;
                        message = message.replace(regx, '');
                        message = message.replace(/\n/g, '<br/>');*/
            message = '<div>' + message + '</div>';
          }
        } else if (ThirdApi.isJSON(message)) {
          message = JSON.parse(message);
          var message1 = "";
          if (message.length) {
            for (var i = 0; i < message.length; i++) {
              message1 += '<div onclick=window.open("' + message[i].url + '")>' +
                '<div style="float: left;width: 60%;padding: 5px"><p>' + message[i].title + '</p><p>' + message[i].description + '</p></div><div style="float: left;width: 30%">' +
                '<img src=' + message[i].picurl + ' style="max-height:100px;max-width:100px;" class="imgZoom" onclick="$.openPhotoGallery(this)"/></div>' +
                '</div>'
            }
            message = message1;
          } else {
            message = '<div><img src=' + message.picurl + ' style="max-height:100px;max-width:100px;"  ondragstart="return false;"  class="imgZoom" onclick="$.openPhotoGallery(this)"/></div>';
          }
        } else if (message.indexOf("http") == 0) {
          message = '<a target="_blank" style="color:blue" href ="' + message + '" >' + message + '</a>';
        } else {

        }
      } else {
        message = message.replace(/\n/g, '<br/>');
      }

      var questList = message.split("[link"); //字符分割

      var newArray = [];
      var jsonObject = JSON.parse("{}");

      for (var i = 0; i < questList.length; i++) {
        if (questList[i].indexOf("[/link]") > -1) {
          var newStr = questList[i];
          var firstIndex = questList[i].indexOf("]") + 1;
          var lastIndex = questList[i].indexOf("[/link]");
          var result = questList[i].substring(firstIndex, lastIndex);
          var jsonData = JSON.parse("{}");
          jsonData.content = result;

          if (newStr.indexOf("submit=") > -1) {
            //机器人回复的link标签中包含submit=
            var titleFirstIndex = newStr.indexOf("submit=");
            var title = newStr.substring(titleFirstIndex + 8, firstIndex - 2);
            //例如="hello"],截取出hello
            jsonData.title = title;
          } else {
            //不包含包含submit=,title给个默认值
            jsonData.title = result;
          }

          newArray.push(jsonData);
        } else {
          jsonObject.title = questList[i];
          newArray.push(questList[i]);
        }
      }

      jsonObject.linkArray = newArray;
      message = '';

      for (var j = 0; j < jsonObject.linkArray.length; j++) {
        if (jsonObject.linkArray[j].content) {
          message += '<li style="color:blue;text-decoration: underline;list-style: none"><pre class="preText">' + jsonObject.linkArray[j].content + '</pre></li>';
        } else {
          message += '<li style="list-style: none"><pre class="preText">' + jsonObject.linkArray[j] + '</pre></li>';
        }
      }
    }
    // 语音
    else if (mediatype == "voice") {
      if (message.indexOf("http") != 0) {

        message = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message;
      }
      message = '<audio class="chatContentActiveAudio" style="max-width:100%;" controls src="' + message + '"></audio>';
    }
    // 图片
    else if (mediatype == "image") {
      var sear1 = new RegExp('bmp');

      if (sear1.test(message)) {
        let downloadUrl = encodeURI(message)
        message = '<a onclick="Utils.downloadUrlFile(\'' + downloadUrl + '\',\'' + fileName + '\')" target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + fileName + '</span></a>';
      } else {
        if (message.indexOf("http") != 0) {
          message = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message;

        }
        message = '<a href="' + message + '"  target="_blank">' + '<img src="' + message + '" style="max-height:100px;max-width:100px;"/></a>'
        // message = '<img src="' + message + '" style="max-height:100px;max-width:100px;" class="imgZoom" onclick="$.openPhotoGallery(this)" ondragstart="return false;"/>';
      }
    }
    // 视频
    else if (mediatype == "video") {
      var sear1 = new RegExp('wmv');
      var sear2 = new RegExp('avi');

      if (sear1.test(message) || sear2.test(message)) {
        let downloadUrl = encodeURI(message)
        message = '<a onclick="Utils.downloadUrlFile(\'' + downloadUrl + '\',\'' + fileName + '\')" target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + fileName + '</span></a>';
      } else {
        if (message.indexOf("http") != 0) {
          message = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message;
        }
        message = '<video style="width: 100%;max-width:250px;" controls src=' + message + '></video>';
      }
    }
    //链接
    else if (mediatype == "link") {
      if (Settings.debugAll) console.log(_typeof(fileName));
      var sear = new RegExp('TUConsent');

      if (sear.test(fileName)) {
        message = customerLang.loan.loan + '<a target="_blank" style="color:blue" href ="' + message + '" >' + customerLang.loan.link + '</a>' + '>';
      } else {
        message = '<a target="_blank" style="color:blue;text-decoration: underline; " href ="' + message + '" >' + fileName + '</a>';
      }
    }
    // 文件
    else {
      if (message.indexOf("http") != 0) {
        message = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message;

      }
      let downloadUrl = encodeURI(message)
      message = '<a onclick="Utils.downloadUrlFile(\'' + downloadUrl + '\',\'' + fileName + '\')" target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + fileName + '</span></a>';
    }
    // 2.显示的消息、图片或音视频
    var headIcon = '<img style="width: 40px;height: 40px;" class="icon meheadPort" src="./static/pro/img/avatar/agentHead.png"/>';
    // if(sort || setHistory){
    // }else{
    //   headIcon = Agent.getCurrentAgent().avatar ? '<img src="'+Agent.getCurrentAgent().avatar+'" style="width: 40px;height: 40px;" class="icon meheadPort">':headIcon
    // }
    if (fromUser == '机器人' || fromUser == i18n.promptMessage.chatTips.System) {
      headIcon = '<img style="width: 40px;height: 40px;" class="icon meheadPort" src="./static/pro/img/avatar/systemHead.png"/>';
    } else {
      fromUser = chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + fromUser;
    }
    var messageTime = new Date(createTime);
    var years = messageTime.getFullYear()
    var mounth = messageTime.getMonth() + 1
    var day = messageTime.getDate()
    var hours = messageTime.getHours()
    var minutes = messageTime.getMinutes()
    if (hours < 10) {
      hours = '0' + hours
    }
    if (minutes < 10) {
      minutes = '0' + minutes
    }
    var inner_html = '';
    // if (Model.people.get_by_sid(Model.people.get_user().sid).hasOwnProperty('messageTimeObj')) {
    //   var leadTime = new Date(createTime) - new Date(Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.realTimes) // 消息间隔时间
    //   if (leadTime >= 1000 * 60 * 5) {
    //     inner_html += '<div style="text-align: center;color: #8f8f91;">' + hours + ':' + minutes + '</div>'
    //     Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.realTimes = createTime
    //   }
    //   // 查看更多消息时间区分时间段
    //   if (viewMoreMessage) {
    //     var moreMessageLeadTime = new Date(Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime) - new Date(createTime) // 历史消息倒叙铺出，moreMessageTimee反过来计算
    //     if (Utils.isToday(createTime)) {
    //       if (moreMessageLeadTime >= 1000 * 60 * 5) {
    //         inner_html += '<div style="text-align: center;color: #8f8f91;">' + hours + ':' + minutes + '</div>'
    //         Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime = createTime
    //       }
    //     } else {
    //       var daysBetween = parseInt(Utils.getDaysBetween(createTime, Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime))
    //       if (daysBetween >= 1 && daysBetween <= 7) {
    //         inner_html += '<div style="text-align: center;color: #8f8f91;">星期' + Utils.getDateWeek(years, mounth, day) + ' ' + hours + ':' + minutes + '</div>'
    //         Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime = createTime
    //       } else if (daysBetween > 7) {
    //         inner_html += '<div style="text-align: center;color: #8f8f91;">' + createTime + '</div>'
    //         Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime = createTime
    //       }
    //       if (daysBetween == 0 && moreMessageLeadTime >= 1000 * 60 * 5) {
    //         inner_html += '<div style="text-align: center;color: #8f8f91;">星期' + Utils.getDateWeek(years, mounth, day) + ' ' + hours + ':' + minutes + '</div>'
    //         Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime = createTime
    //       }
    //     }
    //   }
    // }
    inner_html += '<div class="user retractContent" sessionId="' + sessionId + '" createTime="' + createTime + '" readid="' + uuid + '" retractTime="' + retractTime + '" style="margin-bottom:0px;">' + '<div class="curTime">';
    inner_html += '<span class="pull-right chatCreateTime" style=" margin-left: -60px; margin-right: 60px">&nbsp;&nbsp;' + createTime + '</span><span class="pull-right" title=' + fromUser + ' style="max-width: 163px;overflow: hidden;text-overflow: ellipsis; margin-right: 60px;white-space: nowrap;">' + fromUser + '</span></div>';

    inner_html += headIcon + '<div class="talk_fromMe"></div><div class="chatmsg rightCon">' + message + '</div>' + '</div>';
    if (uuid && AgentApi.checkAuth('Retract')) {
      if (fileName != '座席发起远程协助') {
        inner_html += '<button class="retract">撤回</button>';
      }
    }
    // 发送
    if (!setHistory) {
      if (!sort) {
        if ($(parentEle).find('.chat-robot').length == 0) {
          $(parentEle).append(inner_html);
        } else {
          $(parentEle).find('.chat-robot').before(inner_html);
        }
      } else {
        $(parentEle).prepend(inner_html);
      }
      setTimeout(function () {
        if ($(".chat-interaction-scroll .el-scrollbar__wrap").length > 0) {
          for (let i = 0; i < $(".chat-interaction-scroll .el-scrollbar__wrap").length; i++) {
            $(".chat-interaction-scroll .el-scrollbar__wrap")[i].scrollTop = $(".chat-interaction-scroll .el-scrollbar__wrap")[i].scrollHeight;
          }
        }
        $(window).trigger('resize');
      }, 200);
      // 知识伴随中出现a标签
      if ($(".user .chatmsg").find('a')) {
        $(".user .chatmsg").find('a').click(function () {
          $(this).attr('target', '_black');
        });
      }
      if ($(".user .chatmsg").children().find('img')) {
      } else if ($(".user .chatmsg").children().find('audio')) {
        $(".user .chatmsg").children().find('audio').css('width', '100%');
        $(".user .chatmsg").children().find('audio').css('height', '100%');
      } else if ($(".user .chatmsg").children().find('video')) {
        $(".user .chatmsg").children().find('video').css('width', '100%');
        $(".user .chatmsg").children().find('video').css('height', '100%');
      }

      if (AgentApi.checkAuth(Constants.agentType.SilentChatAgent)) {
      } else {
        if (sort) {
          setTimeout(function () {
            $(".chat-interaction-scroll .el-scrollbar__wrap")[0].scrollTop = 0
            $(window).trigger('resize');
          }, 200);
        } else {
          setTimeout(function () {
            if ($(".chat-interaction-scroll .el-scrollbar__wrap").length > 0) {
              for (let i = 0; i < $(".chat-interaction-scroll .el-scrollbar__wrap").length; i++) {
                $(".chat-interaction-scroll .el-scrollbar__wrap")[i].scrollTop = $(".chat-interaction-scroll .el-scrollbar__wrap")[i].scrollHeight;
              }
            }
            $(window).trigger('resize');
          }, 200);
        }
      }
    } else {
      $(parentEle).append(inner_html);
      return inner_html;
    }
    $(".chat-interaction .chatmsg,.chat-interaction .chatmsg .preText").css({
      fontFamily: Constants.chatFont.fontFamily,
      fontSize: Constants.chatFont.fontSize,
      color: Constants.chatFont.color
    })

    if (!historyFlag) {
      $('.chatCreateTime').css({ 'display': 'none' })
    }
    // 发出的消息气泡鼠标移入移出 创建时间显隐
    $('.chatcontent  .rightCon').on('mouseenter', function () {
      $(this).prev().prev().prev().children()[0].style.display = 'block'
    })
    $('.chatcontent  .rightCon').on('mouseleave', function () {
      $(this).prev().prev().prev().children()[0].style.display = 'none'
    })
  };
  /**
   * 座席自己收到别人的消息，左边显示(入参) sessionId是该消息所属的sessionId,注意，目前历史消息的sessionId会和当前不一致。
   * historyFlag 交互历史详情中显示聊天内容标识 .  firstMessageTomeFlag  客户咨询的第一条消息时间标识
   */
  this.appendChatMessageToMe = function (obj, historyFlag, firstMessageTomeFlag, viewMoreMessage) {
    var parentEle = obj.parentEle || '';
    var sessionId = obj.sessionId || '';
    var message = obj.message || '';
    var mediatype = obj.mediatype || '';
    var toUser = obj.toUser || '';
    var createTime = obj.createTime || '';
    var setHistory = obj.setHistory || '';
    var highLight = obj.highLight || '';
    var filename = obj.fileName || '';
    var sort = obj.sort || '';
    var asrtext = obj.asrtext || '';
    var publisher = obj.publisher || '';
    // 收到EventACK消息不处理
    if (!message || message == "\x04EventACK\x04" || message == 'EventRequestChat' || message == '\x04EventRequestChat\x04') {
      return;
    }
    this.setLastMsg(obj);
    message = chatUiKit.resolveTextToEmotion(message);
    filename = filename || message;
    // var avatar = Constants.basicConfig.clientDefaultAvatar || './pro/interact/assets/multimedia/images/clientHead.png';
    var user = Model.people.get_by_sid(sessionId) || Model.people.get_user();
    if (sessionId && user && publisher == 'client') {
      // if (user.userData.hasOwnProperty('customerStatus') && user.userData.customerStatus == 'logout') { // 匿名头像
      //   avatar = Constants.basicConfig.anonymousAvatar || Constants.basicConfig.clientDefaultAvatar || './pro/interact/assets/multimedia/images/clientHead.png';
      // } else {
      //   if (user.userData.sex == 'male') {
      //     avatar = user.userData.avatar || Constants.basicConfig.manHeadPortrait || Constants.basicConfig.clientDefaultAvatar || './pro/interact/assets/multimedia/images/clientHead.png';
      //   } else if (user.userData.sex == 'female') {
      //     avatar = user.userData.avatar || Constants.basicConfig.womanHeadPortrait || Constants.basicConfig.clientDefaultAvatar || './pro/interact/assets/multimedia/images/clientHead.png';
      //   } else {
      //     avatar = user.userData.avatar || Constants.basicConfig.clientDefaultAvatar || './pro/interact/assets/multimedia/images/clientHead.png';
      //   }
      // }
      if (user.username) {
        toUser = user.username;
      }
    }
    if (publisher == 'agent') {
      // avatar = Constants.basicConfig.agentDefaultAvatar || './pro/interact/assets/multimedia/images/agentHead.png';
    }
    if (publisher == 'system' || mediatype === "systemmsg") {
      toUser = i18n.promptMessage.chatTips.System;
    }
    // 1.各种类型message封装
    // 系统消息
    var sear = new RegExp('http');

    if (sear.test(message)) {
      toUser = toUser || ''
      if (mediatype === "systemmsg") {
        toUser = i18n.promptMessage.chatTips.System;
        message = message.replace(/\n/g, '<br/>');
      }
      //文本
      else if (mediatype === "text" || mediatype === 'transaction') {
        if (message.indexOf('://') == 0 || message.indexOf('http') == 0 || message.indexOf('https') == 0) {
          // message = $.parseHTML(message)
          // // jsonObject.linkArray = newArray
          message = '<a target="_blank" href=' + message + ' style="color:blue;text-decoration: underline;list-style: none"><pre class="preText">' + message + '</pre></a>';
        } else {
          if (message && message.indexOf("pro/interact/multimedia/chat/img/face/") < 0) {
            /*                    message = message.replace(/</g, '&lt;');
                                          message = message.replace(/>/g, '&gt;');
                                          var regx = /<[^>]*>|<\/[^>]*>/gm;
                                          message = message.replace(regx, '');
                                          message = message.replace(/\n/g, '<br/>');*/
            if (ThirdApi.isHtml(message)) {
              var message1 = "";
              if (ThirdApi.isJSON(message)) {
                message = JSON.parse(message);
                if (message.description) {
                  message1 += '<div style="float: left;width: 60%"><p>' + message.description + '</p></div>';
                }
                message1 += '<div class="url" style="float: left;width: 30%">' + message.content + '</div>';
                message = message1;
              } else {
                message = message.replace(/</g, '&lt;');
                message = message.replace(/>/g, '&gt;');
                var regx = /<[^>]*>|<\/[^>]*>/gm;
                message = message.replace(regx, '');
                message = message.replace(/\n/g, '<br/>');
                message = '<div>' + message + '</div>';
              }
            } else if (ThirdApi.isJSON(message)) {
              message = JSON.parse(message);
              var message1 = "";
              if (message.length) {
                for (var i = 0; i < message.length; i++) {
                  message1 += '<div onclick=window.open("' + message[i].url + '")>' +
                    '<div style="float: left;width: 60%;padding: 5px"><p>' + message[i].title + '</p><p>' + message[i].description + '</p></div><div style="float: left;width: 30%">' +
                    '<img src=' + message[i].picurl + ' style="max-height:100px;max-width:100px;" class="imgZoom" onclick="$.openPhotoGallery(this)"/></div>' +
                    '</div>'
                }
                message = message1;
              } else {
                message = '<div><img src=' + message.picurl + ' style="max-height:100px;max-width:100px;"  ondragstart="return false;"  class="imgZoom" onclick="$.openPhotoGallery(this)"/></div>';
              }
            } else if (message.indexOf("http") == 0) {
              message = '<a target="_blank" style="color:blue" href ="' + message + '" >' + message + '</a>';
            } else {

            }
          } else {
            message = message.replace(/\n/g, '<br/>');
          }

          var questList = message.split("[link");
          //字符分割
          var newArray = [];
          var jsonObject = JSON.parse("{}");

          for (var i = 0; i < questList.length; i++) {
            if (questList[i].indexOf("[/link]") > -1) {
              var newStr = questList[i];
              var firstIndex = questList[i].indexOf("]") + 1;
              var lastIndex = questList[i].indexOf("[/link]");
              var result = questList[i].substring(firstIndex, lastIndex);
              var jsonData = JSON.parse("{}");
              jsonData.content = result;

              if (newStr.indexOf("submit=") > -1) {
                //机器人回复的link标签中包含submit=
                var titleFirstIndex = newStr.indexOf("submit=");
                var title = newStr.substring(titleFirstIndex + 8, firstIndex - 2); //例如="hello"],截取出hello

                jsonData.title = title;
              } else {
                //不包含包含submit=,title给个默认值
                jsonData.title = result;
              }

              newArray.push(jsonData);
            } else {
              jsonObject.title = questList[i];
              newArray.push(questList[i]);
            }
          }

          jsonObject.linkArray = newArray;
          message = '';

          for (var j = 0; j < jsonObject.linkArray.length; j++) {
            if (jsonObject.linkArray[j].content) {
              message += '<li style="color:blue;text-decoration: underline;list-style: none"><pre class="preText">' + jsonObject.linkArray[j].content + '</pre></li>';
            } else {
              message += '<li style="list-style: none"><pre class="preText">' + jsonObject.linkArray[j] + '</pre></li>';
            }
          }
        }
        // message = message.replace(/\n/g,'<br/>');
      }
      // 语音
      else if (mediatype == "voice") {
        if (asrtext) {
          message = '<div>' +
            '<div style="height:54px;width:100%;">' +
            '<audio class="chatContentActiveAudio pull-left"  style="max-width:100%;" controls src="' + message + '"></audio>' +
            '<span class="chatContentActiveAudioText pull-left">文</span>' +
            '</div>' +
            '<span style="display:none;">' + asrtext + '</span>' +
            '</div>';
        } else {
          message = '<audio class="chatContentActiveAudio"  style="max-width:100%;" controls src="' + message + '"></audio>';
        }
      }
      // 图片
      // var nessage = 
      else if (mediatype == "image") {
        var sear1 = new RegExp('bmp');

        if (sear1.test(message)) {

          let downloadUrl = encodeURI(message)
          message = '<a onclick="Utils.downloadUrlFile(\'' + downloadUrl + '\',\'' + filename + '\')" target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + filename + '</span></a>';
        } else {
          if (message.indexOf("http") != 0) {
            message = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message;
          }
          message = '<a href="' + message + '"  target="_blank">' + '<img src="' + message + '" style="max-height:100px;max-width:100px;"/></a>'
          // message = '<img src="' + message + '" style="max-height:100px;max-width:100px;" class="imgZoom" onclick="$.openPhotoGallery(this)" ondragstart="return false;"/>';
        }
      }
      // 视频
      else if (mediatype == "video") {
        var sear1 = new RegExp('wmv');
        var sear2 = new RegExp('avi');

        if (sear1.test(message) || sear2.test(message)) {
          let downloadUrl = encodeURI(message)
          message = '<a onclick="Utils.downloadUrlFile(\'' + downloadUrl + '\',\'' + filename + '\')" target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + filename + '</span></a>';
        } else {
          message = '<video  style="width: 100%;max-width: 250px;" controls src="' + message + '"></video>';
        }
      }
      //链接
      else if (mediatype == "link") {
        var sear = new RegExp('TUConsent');
        if (sear.test(message.desc)) {
          message = customerLang.loan.loan + '<a target="_blank" style="color:blue" href ="' + message.resource + '" >' + customerLang.loan.link + '</a>' + '>';
        } else {
          message = '<a target="_blank" style="color:blue" href ="' + message.resource + '" >' + message.desc + '</a>';
        }
      }
      // excel
      else {
        let downloadUrl = encodeURI(message)
        message = '<a onclick="Utils.downloadUrlFile(\'' + downloadUrl + '\',\'' + filename + '\')" target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + filename + '</span></a>';
      }
    }
    else {
      if (mediatype === "systemmsg") {
        toUser = i18n.promptMessage.chatTips.System;
        message = message.replace(/\n/g, '<br/>');
        var questList = message.split("[link");
        //字符分割
        var newArray = [];
        var jsonObject = JSON.parse("{}");

        for (var i = 0; i < questList.length; i++) {
          if (questList[i].indexOf("[/link]") > -1) {
            var newStr = questList[i];
            var firstIndex = questList[i].indexOf("]") + 1;
            var lastIndex = questList[i].indexOf("[/link]");
            var result = questList[i].substring(firstIndex, lastIndex);
            var jsonData = JSON.parse("{}");
            jsonData.content = result;

            if (newStr.indexOf("submit=") > -1) {
              //机器人回复的link标签中包含submit=
              var titleFirstIndex = newStr.indexOf("submit=");
              var title = newStr.substring(titleFirstIndex + 8, firstIndex - 2);
              //例如="hello"],截取出hello
              jsonData.title = title;
            } else {
              //不包含包含submit=,title给个默认值
              jsonData.title = result;
            }

            newArray.push(jsonData);
          } else {
            jsonObject.title = questList[i];
            newArray.push(questList[i]);
          }
        }

        jsonObject.linkArray = newArray;
        message = '';
        for (var j = 0; j < jsonObject.linkArray.length; j++) {
          if (jsonObject.linkArray[j].content) {
            message += '<li style="color:blue;text-decoration: underline;list-style: none"><pre class="preText">' + jsonObject.linkArray[j].content + '</pre></li>';
          } else {
            message += '<li style="list-style: none"><pre class="preText">' + jsonObject.linkArray[j] + '</pre></li>';
          }
        }
      }
      //文本
      else if (mediatype === "text" || mediatype === 'transaction' || mediatype == 'satisfaction') {
        if (message && message.indexOf("pro/interact/multimedia/chat/img/face/") < 0) {
          message = message.replace(/</g, '&lt;');
          message = message.replace(/>/g, '&gt;');
          var regx = /<[^>]*>|<\/[^>]*>/gm;
          message = message.replace(regx, '');
          message = message.replace(/\n/g, '<br/>');
        } else {
          message = message.replace(/\n/g, '<br/>');
        }
        var questList = message.split("[link");
        //字符分割
        var newArray = [];
        var jsonObject = JSON.parse("{}");

        for (var i = 0; i < questList.length; i++) {
          if (questList[i].indexOf("[/link]") > -1) {
            var newStr = questList[i];
            var firstIndex = questList[i].indexOf("]") + 1;
            var lastIndex = questList[i].indexOf("[/link]");
            var result = questList[i].substring(firstIndex, lastIndex);
            var jsonData = JSON.parse("{}");
            jsonData.content = result;

            if (newStr.indexOf("submit=") > -1) {
              //机器人回复的link标签中包含submit=
              var titleFirstIndex = newStr.indexOf("submit=");
              var title = newStr.substring(titleFirstIndex + 8, firstIndex - 2); //例如="hello"],截取出hello
              jsonData.title = title;
            } else {
              //不包含包含submit=,title给个默认值
              jsonData.title = result;
            }
            newArray.push(jsonData);
          } else {
            jsonObject.title = questList[i];
            newArray.push(questList[i]);
          }
        }
        jsonObject.linkArray = newArray;
        message = '';
        for (var j = 0; j < jsonObject.linkArray.length; j++) {
          if (jsonObject.linkArray[j].content) {
            message += '<li style="color:blue;text-decoration: underline;list-style: none"><pre class="preText">' + jsonObject.linkArray[j].content + '</pre></li>';
          } else {
            message += '<li style="list-style: none"><pre class="preText">' + jsonObject.linkArray[j] + '</pre></li>';
          }
        }
      }
      // 语音
      else if (mediatype == "voice") {
        if (asrtext) {
          message = '<div>' +
            '<div style="height:54px;width:100%;">' +
            '<audio class="chatContentActiveAudio pull-left"  style="max-width:100%;" controls src=' + window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message + '></audio>' +
            '<span class="chatContentActiveAudioText pull-left">文</span>' +
            '</div>' +
            '<span style="display:none;">' + asrtext + '</span>' +
            '</div>';
        } else {
          message = '<audio class="chatContentActiveAudio"  style="max-width:100%;" controls src=' + window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message + '></audio>';
        }
      }
      // 图片
      else if (mediatype == "image") {
        var sear1 = new RegExp('bmp');

        if (sear1.test(message)) {
          let downloadUrl = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + encodeURI(message)
          message = '<a onclick="Utils.downloadUrlFile(\'' + downloadUrl + '\',\'' + filename + '\')" target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + filename + '</span></a>';
        } else {
          let url = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message;
          message = '<a href="' + url + '"  target="_blank">' + '<img src="' + url + '" style="max-height:100px;max-width:100px;"/></a>'
          // message = '<img src=' + window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message + ' style="max-height:100px;max-width:100px;" class="imgZoom"  onclick="$.openPhotoGallery(this)"ondragstart="return false;"/>';
        }
      }

      // 视频https://devcc.myegoo.com.cn/fileserver
      else if (mediatype == "video") {
        var sear1 = new RegExp('wmv');
        var sear2 = new RegExp('avi');

        if (sear1.test(message) || sear2.test(message)) {

          let downloadUrl = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + encodeURI(message)
          message = '<a target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " href =' + window.CONFIG.baseRestIp + '/fileserver/get?filename=' + encodeURI(message) + ' class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + filename + '</span></a>';
        } else {
          message = '<video  style="width: 100%;max-width: 250px;" controls src=' + window.CONFIG.baseRestIp + '/fileserver/get?filename=' + message + '></video>';
        }
      } else if (mediatype == "link") {
        var sear = new RegExp('TUConsent');

        if (sear.test(message.desc)) {
          message = customerLang.loan.loan + '<a target="_blank" style="color:blue" href ="' + message.resource + '" >' + customerLang.loan.link + '</a>' + '>';
        } else {
          message = '<a target="_blank" style="color:blue" href ="' + message.resource + '" >' + message.desc + '</a>';
        }
      }
      // excel
      else {

        let downloadUrl = window.CONFIG.baseRestIp + '/fileserver/get?filename=' + encodeURI(message)
        message = '<a onclick="Utils.downloadUrlFile(\'' + downloadUrl + '\',\'' + filename + '\')" target="_blank" style="float: right;width: 200px;text-decoration: underline;background:url(./pro/interact/assets/multimedia/images/wenjian.png) no-repeat;background-position: center right " class="fromuser"  ondragstart="return false;"><span style="display: block;width: 150px">' + filename + '</span></a>';
      }
    }

    // 2.显示的消息、图片或音视频
    toUser = toUser || ''
    toUser = toUser.replace(/</g, '&lt;');
    toUser = toUser.replace(/>/g, '&gt;');
    var regx1 = /<[^>]*>|<\/[^>]*>/gm;
    toUser = toUser.replace(regx1, '');
    var messageTime = new Date(createTime);
    var years = messageTime.getFullYear()
    var mounth = messageTime.getMonth() + 1
    var day = messageTime.getDate()
    var hours = messageTime.getHours()
    var minutes = messageTime.getMinutes()
    if (hours < 10) {
      hours = '0' + hours
    }
    if (minutes < 10) {
      minutes = '0' + minutes
    }
    var inner_html = '';
    // if (Model.people.get_by_sid(Model.people.get_user().sid).hasOwnProperty('messageTimeObj')) {
    //   var leadTime = new Date(createTime) - new Date(Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.realTimes) // 相信消息间隔时间
    //   if (firstMessageTomeFlag || leadTime >= 1000 * 60 * 5) {
    //     inner_html += '<div style="text-align: center;color: #8f8f91;">' + hours + ':' + minutes + '</div>'
    //     Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.realTimes = createTime
    //   }
    //   // 查看更多消息时间区分时间段
    //   if (viewMoreMessage) {
    //     var moreMessageLeadTime = new Date(Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime) - new Date(createTime) // 历史消息倒叙铺出，moreMessageTimee反过来计算
    //     if (Utils.isToday(createTime)) {
    //       if (moreMessageLeadTime >= 1000 * 60 * 5) {
    //         inner_html += '<div style="text-align: center;color: #8f8f91;">' + hours + ':' + minutes + '</div>'
    //         Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime = createTime
    //       }
    //     } else {
    //       var daysBetween = parseInt(Utils.getDaysBetween(createTime, Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime))
    //       if (daysBetween >= 1 && daysBetween <= 7) {
    //         inner_html += '<div style="text-align: center;color: #8f8f91;">星期' + Utils.getDateWeek(years, mounth, day) + ' ' + hours + ':' + minutes + '</div>'
    //         Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime = createTime
    //       } else if (daysBetween > 7) {


    //         inner_html += '<div style="text-align: center;color: #8f8f91;">' + createTime + '</div>'
    //         Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime = createTime
    //       }
    //       if (daysBetween == 0 && moreMessageLeadTime >= 1000 * 60 * 5) {
    //         inner_html += '<div style="text-align: center;color: #8f8f91;">星期' + Utils.getDateWeek(years, mounth, day) + ' ' + hours + ':' + minutes + '</div>'
    //         Model.people.get_by_sid(Model.people.get_user().sid).messageTimeObj.moreMessageTime = createTime
    //       }
    //     }
    //   }
    // }
    inner_html += '<div class="user" sessionId="' + sessionId + '" createTime="' + createTime + '">' + '<div class="curTime">';
    inner_html += '<span class="pull-left" title=' + toUser + ' style="max-width: 163px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap; margin-left: 60px">' + toUser + '</span><span class="pull-left chatCreateTime" >&nbsp;&nbsp;' + (createTime || chatUiKit.getServerTime()) + '</span></div>';
    var headIcon = '<img style="width: 40px;height: 40px;" class="icon meheadPort" src="./static/pro/img/avatar/customHead.png"/>';
    if (toUser == i18n.promptMessage.chatTips.System) {
      headIcon = '<img style="width: 40px;height: 40px;" class="icon meheadPort" src="./static/pro/img/avatar/systemHead.png"/>';
    }
    inner_html += '<div class="headPort">' + headIcon + '</div><div class="talk_toMe"></div>';
    // 高亮显示
    if (highLight) {
      inner_html += '<div class="leftConCoach chatmsg">' + message + '</div>' + '</div>';
    } else {
      inner_html += '<div class="leftCon chatmsg">' + message + '</div>' + '</div>';
    }
    // 3.添加到聊天窗口
    if (!setHistory) {
      if (!sort) {
        if ($(parentEle).find('.chat-robot').length == 0) {
          $(parentEle).append(inner_html);
        } else {
          $(parentEle).find('.chat-robot').before(inner_html);
        }
      } else {
        $(parentEle).prepend(inner_html);
      }
      setTimeout(function () {
        if ($(".chat-interaction-scroll .el-scrollbar__wrap").length > 0) {
          for (let i = 0; i < $(".chat-interaction-scroll .el-scrollbar__wrap").length; i++) {
            $(".chat-interaction-scroll .el-scrollbar__wrap")[i].scrollTop = $(".chat-interaction-scroll .el-scrollbar__wrap")[i].scrollHeight;
          }
        }
        $(window).trigger('resize');
      }, 200);
      // 知识伴随中出现a标签
      if ($(".user .chatmsg").find('a')) {
        $(".user .chatmsg").find('a').click(function () {
          $(this).attr('target', '_black');
        });
      }

      if ($(".user .chatmsg").children().find('img')) {
      } else if ($(".user .chatmsg").children().find('audio')) {
        $(".user .chatmsg").children().find('audio').css('width', '100%');
        $(".user .chatmsg").children().find('audio').css('height', '100%');
      } else if ($(".user .chatmsg").children().find('video')) {
        $(".user .chatmsg").children().find('video').css('width', '100%');
        $(".user .chatmsg").children().find('video').css('height', '100%');
      }

      if (AgentApi.checkAuth(Constants.agentType.SilentChatAgent)) {
      } else {
        if (sort) {
          setTimeout(function () {
            $(window).trigger('resize');
          }, 200);
        } else {
          if ($(".chat-interaction-scroll .el-scrollbar__wrap").length > 0) {
            for (let i = 0; i < $(".chat-interaction-scroll .el-scrollbar__wrap").length; i++) {
              $(".chat-interaction-scroll .el-scrollbar__wrap")[i].scrollTop = $(".chat-interaction-scroll .el-scrollbar__wrap")[i].scrollHeight;
            }
          }
        }
      }
    } else {
      $(parentEle).append(inner_html);
      return inner_html;
    }
    $(".chat-interaction .chatmsg,.chat-interaction .chatmsg .preText").css({
      fontFamily: Constants.chatFont.fontFamily,
      fontSize: Constants.chatFont.fontSize,
      color: Constants.chatFont.color
    })
    if (!historyFlag) {
      $('.chatCreateTime').css({ 'display': 'none' })
    }
    // 收到的消息气泡鼠标移入移出 创建时间显隐
    $('.chatcontent  .leftCon').on('mouseenter', function () {
      $(this).prev().prev().prev().children()[1].style.display = 'block'
    })
    $('.chatcontent  .leftCon').on('mouseleave', function () {
      $(this).prev().prev().prev().children()[1].style.display = 'none'
    })
  };
  this.setLastMsg = function (obj) {
    var msg = obj.message;
    switch (obj.mediatype) {
      case 'image': {
        msg = '[图片]';
        break
      }
      case 'voice': {
        msg = '[音频]';
        break
      }
      case 'video': {
        msg = '[视频]';
        break
      }
      case "word":
      case "excel":
      case "pdf":
      case "ppt":
      case "txt": {
        msg = '[文档]';
        break
      }
      case "link": {
        msg = '[链接]';
        break
      }
      default: {
        break
      }
    }
    Model.people.setLastMsg(obj.sessionId, { msg: msg, msgtype: obj.mediatype })
  };
  /**
   * 文件上传功能
   * @param event
   * @param id
   */
  this.uploadFile = function (event, id) {
    if (event.currentTarget.files.length > 0) {
      let curUser = Model.people.get_user()
      if (!curUser) {
        return
      }
      if (!navigator.onLine) {
        globalUiKit.notify('', i18n.promptMessage.chatTips.navigatorOffline, 'warning');
        return;
      }
      let maxlen = 1
      let fileNumInfo = '';
      if (id == 'trans_img') {
        maxlen = window.Settings.chat.maxImgNo;
        fileNumInfo = i18n.promptMessage.chatTips.imgNumInfo1 + maxlen + i18n.promptMessage.chatTips.imgNumInfo2;
      }
      else if (id == 'trans_file') {
        maxlen = window.Settings.chat.maxFileNo;
        fileNumInfo = i18n.promptMessage.chatTips.fileNumInfo1 + maxlen + i18n.promptMessage.chatTips.fileNumInfo2;
      }
      if (id == 'trans_img' || id == 'trans_file') {
        if (event.currentTarget.files.length > maxlen) {
          globalUiKit.notify('', fileNumInfo)
          event.currentTarget.value = '';
          return;
        }
      }
      for (let m = 0; m < event.currentTarget.files.length; m++) {
        var file = event.currentTarget.files[m];
        // 获取文件后缀名索引
        var suffixIndex = file.name.lastIndexOf(".")
        // 获取文件后缀名
        var suffix = file.name.substring(suffixIndex + 1).toLowerCase()
        var msgType = Utils.getFileType(suffix)
        // 针对图片文件 后台转码会将其他格式文件转为jpg格式
        if ('image' == msgType) {
          suffix = 'jpg'
        }
        let url = Utils.getUploadFileUrl(suffix)
        let formData = new FormData()
        formData["enctype"] = 'multipart/form-data'
        formData.append("file", file)
        // 上传图片时对类型做限制
        let fileName = file.name
        formData.append("file_name", fileName)
        // 对上传文件大小做限制
        if (file.size) {
          let size = file.size / 1024 / 1024;
          if (!("image" === msgType || "voice" === msgType || "video" === msgType) && window.Settings.fileLimit < size) {
            globalUiKit.notify('', i18n.promptMessage.chatTips.fileLimit);
            event.currentTarget.value = '';
            return;
          }
          if ("image" == msgType && window.Settings.fileLimit < size) {
            globalUiKit.notify('', i18n.promptMessage.chatTips.imageLimit);
            event.currentTarget.value = '';
            return;
          }
          if ("voice" == msgType && window.Settings.fileLimit < size) {
            globalUiKit.notify('', i18n.promptMessage.chatTips.voiceLimit);
            event.currentTarget.value = '';
            return;
          }
          if ("video" == msgType && window.Settings.fileLimit < size) {
            globalUiKit.notify('', i18n.promptMessage.chatTips.videoLimit);
            event.currentTarget.value = '';
            return;
          }
        } else {
          globalUiKit.notify('', i18n.promptMessage.chatTips.fileEmpty);
          event.currentTarget.value = '';
          return;
        }
        chatUiKit.requestUploadFile(url, formData, msgType, fileName);
        event.currentTarget.value = '';
      }
    }
  }

  this.requestUploadFile = function (url, formData, msgType, fileName) {
    let curUser = Model.people.get_user()
    var fileUploadRequest = $.ajax({
      url: url,
      type: 'post',
      async: true,
      contentType: false,
      processData: false,
      data: formData,
      dataType: 'text',
      timeout: Settings.ajaxRequestTimeout * 3,
      success: function success (data) {
        if (data && data != 'failure') {
          if (Settings.debugAll) {
            console.log(new Date() + ",log info [文件异步上传成功: " + data + "]");
          }
          // 判断返回的值是否包含code
          if (data.indexOf('code') > -1) {
            var fileData = JSON.parse(data);
            if (fileData.code) {
              globalUiKit.notify('', '上传文件失败!');
            }
          } else {
            console.log(data)
            let path = data
            let mediaId = ''
            if (curUser && ('wechat' === curUser.chatType || 'wework' === curUser.chatType)) {
              if (Constants.wechatMode == 'original') {
                path = data.split(',')[1]
                mediaId = data.split(',')[0]
              }
            }
            let obj = {}
            obj.msgtype = msgType
            obj.content = path
            obj.mediaid = mediaId
            obj.filename = fileName
            chatUiKit.sendCurrentUsrMsg(obj)
          }
        } else {
          globalUiKit.notify('', '上传文件失败!');
        }
      },
      error: function error (XMLHttpRequest, textStatus, errorThrown) {
        if (textStatus != 'timeout') {
          if (Settings.debugAll) console.log(new Date() + "上传文件失败 " + textStatus + " : " + errorThrown);
        }
      },
      complete: function complete (XMLHttpRequest, status) {
        if (Settings.debugAll) {
          console.log(new Date() + "异步上传文件完成 : " + status);
        }
        if ('timeout' === status) {
          fileUploadRequest.abort();
        }
      }
    })
  }

  this.requestRtc = function (requestType) {
    if (Model.people.get_users_by_channeltype('call') > 0) {
      globalUiKit.alert('', '正在电话通话中，请先挂断后再发起！')
      return;
    }
    let curUser = Model.people.get_user()
    if (!curUser || curUser.chatState === 'ChatDone') {
      if (Settings.debugAll) {
        console.log(new Date() + '当前无会话或当前会话已结束，不能发起语音电话')
      }
      return
    }
    if (!navigator.onLine) {
      globalUiKit.notify('', i18n.promptMessage.lobibox.failVoice, 'warning')
      return
    }
    if ('wechat' === curUser.chatType) {
      globalUiKit.alert('', '微信渠道暂不支持音频通话！')
      return
    }
    // 视频正在通话中
    if (webRtcUiKit.getmyjson().chatroom) {
      globalUiKit.alert('', '请先结束音视频通话或协同浏览！');
    }
    else {
      let enableVideo = ''
      let content = ''
      let agentContent = ''
      let confirmTip = ''
      if ('voice' == requestType) {
        enableVideo = 'voicestart'
        content = customerLang.tip.agentVoiceRequset || ''
        agentContent = i18n.promptMessage.chatTips.agentVoiceRequset || ''
        confirmTip = i18n.promptMessage.chatTips.voiceRequest || ''
      }
      else if ('video' == requestType) {
        enableVideo = 'videostart'
        content = customerLang.tip.agentAudioRequest || ''
        agentContent = i18n.promptMessage.chatTips.agentAudioRequest || ''
        confirmTip = i18n.promptMessage.chatTips.agentAudioRequest || ''
      }
      else if ('share' == requestType) {
        enableVideo = 'start_cobrower'
        content = '座席发起远程协助' || ''
        agentContent = '座席发起远程协助' || ''
        confirmTip = i18n.promptMessage.chatTips.WebPageCollaborationRequest || ''
      }

      globalUiKit.confirm('', confirmTip, function () {
        var roomId = new Date().getTime()
        // 打开视频窗口
        if (CONFIG.RTC.rtcType == "LTRtc" && 'xiaochengxu' === curUser.chatType) {
          tRtcUiKit.joinConference(roomId, Agent.getCurrentAgent().agentId, CONFIG.RTC.parentid, { sessionId: curUser.sid });
        } else {
          var auths = AgentApi.getVideoAuths();
          webRtcUiKit.joinConference(curUser.sid, Agent.getCurrentAgent().agentId, CONFIG.RTC.parentid, 'Agent', requestType, {
            channeltype: curUser.chatType,
            otherdn: curUser.uid,
            record: true,
            turn: CONFIG.RTC.turn,
            tenantid: Agent.getCurrentAgent().tenantId
          }, { auths: auths })
        }
        // 发送消息封装
        let obj = {}
        obj.agentContent = agentContent
        obj.content = content
        obj.msgtype = 'text'
        obj.enablevideo = enableVideo
        obj.userdata = { rtcType: "LTRtc", "roomId": roomId }
        chatUiKit.sendCurrentUsrMsg(obj)
      }, function () {
      })
    }
  }

  // 满意度评价
  this.evaluate = function (sessionId) {
    if (!Model.people.get_user() || Model.people.get_user().chatState === 'ChatDone') {
      globalUiKit.alert('提示信息', '当前客户不存在或不在通话中，不能转满意度！')
      return;
    }
    // 发送消息封装
    let obj = {}
    obj.content = '发送满意度评价成功。'
    obj.msgtype = 'satisfaction'
    obj.textEvaluate = true
    if (sessionId) {
      obj.sessionId = sessionId
    }
    chatUiKit.sendCurrentUsrMsg(obj)
  }
  // --orderuse
  this.showChatHistoryDetail = function (ele, sesContent, agentId, historyFlag) {
    let messageJson = {}
    if (sesContent) {
      for (var j = 0; j < sesContent.length; j++) {
        // 2.3.1 添加座席自己发送的消息
        if (sesContent[j].fromuser === agentId) {
          var msgType = sesContent[j].msgtype;
          var message = sesContent[j].content;
          var createTime = sesContent[j].createtime;
          var fileName = sesContent[j].filename || '';
          if ('link' === msgType) {
            var s = JSON.parse(message)
            message = s.resource
            fileName = s.desc
          }
          messageJson.parentEle = ele
          messageJson.sessionId = ''
          messageJson.message = message
          messageJson.mediatype = msgType
          messageJson.fileName = fileName
          messageJson.fromUser = sesContent[j].nickname || agentId
          messageJson.createTime = createTime
          messageJson.setHistory = true
          messageJson.publisher = sesContent[j].publisher
          chatUiKit.appendChatMessageFromMe(messageJson)
        }
        // 从座席发出的消息（右边显示）,机器人发的
        else if (sesContent[j].fromuser === null && sesContent[j].touser !== agentId) {
          var msgType = sesContent[j].msgtype;
          var message = sesContent[j].content;
          var createTime = sesContent[j].createtime;
          if ('text' === msgType || 'systemmsg' === msgType) {

          } else if ('image' === msgType || 'voice' === msgType || 'video' === msgType) {
            message = message;
            if (Settings.debugAll) console.log(message);
          } else if ('link' === msgType) {
            var s = JSON.parse(message)
            message = s.resource
          }
          messageJson.parentEle = ele
          messageJson.sessionId = ''
          messageJson.message = message
          messageJson.mediatype = msgType
          messageJson.fileName = ''
          messageJson.fromUser = '机器人'
          messageJson.createTime = createTime
          messageJson.setHistory = true
          messageJson.publisher = sesContent[j].publisher
          chatUiKit.appendChatMessageFromMe(messageJson, historyFlag)
        }
        // 2.3.2 添加对方发送的消息
        else {
          var msgType = sesContent[j].msgtype;
          var message = sesContent[j].content;
          var createTime = sesContent[j].createtime;
          var fromuser = '';
          var fileName = sesContent[j].filename || '';
          if ('text' === msgType || 'systemmsg' === msgType) {

          } else if ('image' === msgType || 'voice' === msgType || 'video' === msgType) {
            message = message;
          } else if ('link' === msgType) {
            var s = JSON.parse(message)
            message = s.desc
          }
          var userName = '';
          if (sesContent[j].nickname) {
            userName = sesContent[j].nickname.replace(/</g, '&lt;');
            userName = userName.replace(/>/g, '&gt;');
            var regx1 = /<[^>]*>|<\/[^>]*>/gm;
            userName = userName.replace(regx1, '');
            fromuser = userName;
          } else {
            fromuser = sesContent[j].fromuser;
          }
          messageJson.parentEle = ele
          messageJson.sessionId = ''
          messageJson.message = message
          messageJson.mediatype = msgType
          messageJson.toUser = fromuser
          messageJson.createTime = createTime
          messageJson.setHistory = true
          messageJson.highLight = ''
          messageJson.sid = ''
          messageJson.fileName = fileName
          messageJson.publisher = sesContent[j].publisher
          self.appendChatMessageToMe(messageJson, historyFlag)
        }
      }
    }
  };


  /**
   * 路径转成表情
   */
  this.resolveTextToEmotion = function (str) {
    if (!str) {
      return ''
    }
    if (typeof str == 'string' && str.indexOf('[') > -1) {
      for (let i = 0; i < Options.multimedia.faceEmoji.length; i++) {
        let ele = Options.multimedia.faceEmoji[i]
        str = str.replace(new RegExp('\\' + ele.alt.substr(0, ele.alt.length - 1) + '\\]', "g"), '<img src=' + ele.src + ' style="width:25px;height:25px"/>')
      }
    }
    return str
  };

  /**************************************************************************************
   *********************************** 当前客户发送消息 ************************************
   **************************************************************************************/
  this.sendCurrentUsrMsg = function (obj) {
    let curUser = Model.people.get_by_sid(obj.sessionId) || Model.people.get_user();
    if (!curUser) {
      return;
    }
    if (!navigator.onLine) {
      globalUiKit.notify('', i18n.promptMessage.chatTips.navigatorOffline, 'warning');
      return;
    }
    let messageJson = {}
    let userId = curUser.uid
    let chatType = curUser.chatType
    let chatMode = 'normal'
    let agentId = Agent.getCurrentAgent().agentId
    let uuid = obj.readid || Utils.uuid()
    let messageText = new Object();
    let sessionId = curUser.sid
    // 判断是否为咨询页面发送
    if (sessionId.indexOf(Constants.multimedia.consultPrefix) > -1) {
      sessionId = sessionId.replace(Constants.multimedia.consultPrefix, '')
    }
    messageText.mediaid = obj.mediaid || ''
    messageText.msgtype = obj.msgtype || ''
    messageText.content = filterXSS(obj.content || '')
    messageText.filename = obj.filename || ''
    messageText.touser = userId || ''
    messageText.fromuser = agentId || ''
    messageText.channeltype = chatType || ''
    messageText.interactionid = sessionId || ''
    messageText.chatmode = chatMode || ''
    messageText.genderMap = Agent.getCurrentAgent().genderMap || ''
    messageText.nickname = chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + Agent.getCurrentAgent().nickName
    messageText.enablevideo = obj.enablevideo || ''
    messageText.userdata = {
      'readid': uuid
    }
    if (obj.robotUserData) {
      messageText.robotUserData = obj.robotUserData
    }
    // 是否为座席内部之间发送消息
    if (['coach', 'ChatCoach', 'ChatUC'].indexOf(curUser.chatState) > -1) {
      chatSDK.sendChatMsg(sessionId, messageText, 'INT');
    } else {
      messageText.issilentagent = AgentApi.checkAuth(Constants.agentType.SilentChatAgent)
      chatSDK.sendChatMsg(sessionId, messageText);
    }
    // 如果为信令消息，不走显示逻辑 语音电话 消息撤回
    var msgtypeList = ['retract', 'satisfaction', 'webcall', 'EventInputStart', 'EventInputEnd']
    if (messageText.content.length === 0 || msgtypeList.indexOf(obj.msgtype) > -1) {
      if (obj.hasOwnProperty('textEvaluate')) {
        obj.msgtype = 'text';
      } else {
        return
      }
    }
    chatUiKit.clearIntervalAgentSession(sessionId);
    window.globalUiKit.vm.$emit('agentSessionTimeOut', { sessionId: sessionId, agentSessionTimeOut: 'agentSessionTimeOutGreen' });
    chatUiKit.clearIntervalSession(sessionId);
    AppEventHandler.intervalClock(sessionId);
    messageJson.parentEle = $('.chatcontent[name="' + curUser.sid + '"]')
    messageJson.sessionId = curUser.sid
    messageJson.message = filterXSS(obj.agentContent || obj.content)
    messageJson.mediatype = obj.msgtype
    messageJson.fileName = obj.filename || ''
    messageJson.fromUser = Agent.getCurrentAgent().nickName
    messageJson.createTime = ''
    messageJson.setHistory = ''
    messageJson.uuid = uuid
    chatUiKit.appendChatMessageFromMe(messageJson)
  }

  /**************************************************************************************
   ************************************* 处理结束逻辑 ************************************
   **************************************************************************************/
  this.endChatAction = function (sessionId) {
    // 1.0、会话内容
    $('.chatcontent[name="' + sessionId + '"]').remove();
    globalUserData.chatDone(sessionId);
    Model.people.on_exit_chat(sessionId);
    // 1.3 清除机器人答案上报全局变量
    delete firstAnswerFlag[sessionId];
    delete queryIdMap[sessionId];
    var count = Object.keys(Model.people.get_all_users()).length;
    // 3、没有其他用户直接清空
    if (0 === count) {
      workbenchApp.initChatRecord() //初始化頁面
    }
    resetAgentStatus();
  }
  // 结束聊天按钮
  this.endChatUC = function () {
    if (!Model.people.get_user() || Model.people.get_user().chatState === 'ChatDone') {
      return
    }
    let curUser = Model.people.get_user();
    chatSDK.requestChatControl(chatSDK.actions.ActionChatQuitUC, curUser.sid);
    let messageJson = {}
    messageJson.parentEle = $('.chatcontent[name=' + curUser.sid + ']')
    messageJson.sessionId = curUser.sid
    messageJson.message = i18n.promptMessage.chatTips.AgentLeft
    messageJson.mediatype = 'text'
    messageJson.fileName = ''
    messageJson.fromUser = Agent.getCurrentAgent().nickName
    chatUiKit.appendChatMessageFromMe(messageJson)
  }

  this.sendVideoHangupMsg = function (sessionId) {
    var userVideo = Model.people.get_by_sid(sessionId);
    if (userVideo) {
      if (userVideo.chatState == Constants.chatState.Normal || userVideo.chatState == "normal" || userVideo.chatState == "transfer") {
        var messageText = new Object();
        messageText.msgtype = "text";
        messageText.touser = userVideo.uid;
        messageText.fromuser = Agent.getCurrentAgent().agentId;
        messageText.channeltype = userVideo.chatType;
        messageText.interactionid = sessionId;
        messageText.chatmode = "normal";
        messageText.issilentagent = "false";
        messageText.enablevideo = 'hangup';
        chatSDK.sendChatMsg(sessionId, messageText);
      }
      var messageText = new Object();
      messageText.msgtype = "text";
      messageText.content = Agent.getCurrentAgent().agentId + i18n.promptMessage.chatTips.agentEndVideo
      messageText.touser = userVideo.uid;
      messageText.fromuser = Agent.getCurrentAgent().agentId;
      messageText.channeltype = userVideo.chatType;
      messageText.interactionid = sessionId;
      messageText.chatmode = "normal";
      messageText.issilentagent = "false";
      messageText.enablevideo = '';
      chatSDK.sendChatMsg(sessionId, messageText);
      let messageJson = {}
      messageJson.parentEle = $('.chatcontent[name=' + sessionId + ']')
      messageJson.sessionId = sessionId
      messageJson.message = Agent.getCurrentAgent().agentId + i18n.promptMessage.chatTips.agentEndVideo
      messageJson.mediatype = 'text'
      messageJson.fileName = ''
      messageJson.fromUser = Agent.getCurrentAgent().nickName
      chatUiKit.appendChatMessageFromMe(messageJson)
    }
  }
  this.sendStartWhiteboardMsg = function (sessionId) {
    var userVideo = Model.people.get_by_sid(sessionId);
    if (userVideo) {
      var messageText = new Object();
      messageText.msgtype = "startwhiteboard";
      messageText.content = Agent.getCurrentAgent().agentId + "发起白板";
      messageText.touser = userVideo.uid;
      messageText.fromuser = Agent.getCurrentAgent().agentId;
      messageText.channeltype = userVideo.chatType;
      messageText.interactionid = sessionId;
      messageText.chatmode = "normal";
      messageText.issilentagent = "false";
      messageText.enablevideo = '';
      chatSDK.sendChatMsg(sessionId, messageText);
      let messageJson = {}
      messageJson.parentEle = $('.chatcontent[name=' + sessionId + ']')
      messageJson.sessionId = sessionId
      messageJson.message = Agent.getCurrentAgent().agentId + "发起白板"
      messageJson.mediatype = 'text'
      messageJson.fileName = ''
      messageJson.fromUser = Agent.getCurrentAgent().nickName
      chatUiKit.appendChatMessageFromMe(messageJson)
    }
    window.open(CONFIG.whiteboardUrl);
  }
  this.sendRemoteAssistanceMsg = function () {
    var userVideo = Model.people.get_user();
    if (userVideo) {
      var messageText = new Object();
      messageText.msgtype = "eCobrowser";
      messageText.content = "https://devcc.egooccs.com/TeamWork/index.html";
      messageText.touser = userVideo.uid;
      messageText.fromuser = Agent.getCurrentAgent().agentId;
      messageText.channeltype = userVideo.chatType;
      messageText.interactionid = userVideo.sid;
      messageText.chatmode = "normal";
      messageText.issilentagent = "false";
      messageText.enablevideo = '';
      chatSDK.sendChatMsg(userVideo.sid, messageText);
      let messageJson = {}
      messageJson.parentEle = $('.chatcontent[name=' + userVideo.sid + ']')
      messageJson.sessionId = userVideo.sid
      messageJson.message = Agent.getCurrentAgent().agentId + "远程协助"
      messageJson.mediatype = 'text'
      messageJson.fileName = ''
      messageJson.fromUser = Agent.getCurrentAgent().nickName
      chatUiKit.appendChatMessageFromMe(messageJson)
      window.open("https://devcc.egooccs.com/TeamWork/index.html?fromuser=" + Agent.getCurrentAgent().agentId + "&chatroom=" + userVideo.sid)
    }
  }
  // 发送风险提示
  this.sendRiskwarningMsg = function (sessionId) {
    var curUser = Model.people.get_user();
    if (sessionId) {
      curUser = Model.people.get_by_sid(sessionId);
    }
    if (curUser) {
      if (curUser.chatState == Constants.chatState.Normal || curUser.chatState == "normal") {
        var messageText = new Object();
        messageText.msgtype = "riskwarning";
        messageText.touser = curUser.uid;
        messageText.fromuser = Agent.getCurrentAgent().agentId;
        messageText.channeltype = curUser.chatType;
        messageText.interactionid = curUser.sid;
        messageText.chatmode = "normal";
        messageText.issilentagent = "false";
        messageText.content = "安全风险提示：。。。。。";
        chatSDK.sendChatMsg(curUser.sid, messageText);
      }
    }
  }

  // 点击消息显示撤回按钮
  $('.chat-interaction').on('click', '.chatmsg', function () {
    if (AgentApi.checkAuth('Retract')) {
      var curUser = Model.people.get_user();
      // 获取每条消息的readid
      var readid = $(this).parent().attr('readid');
      // 获取发送消息时间
      var retractTime = $(this).parent().attr('retractTime');
      var retractTimeout = Utils.retractTimeDifference(retractTime);
      console.log(retractTimeout)
      if (readid && readid != "undefined") {
        if (curUser.chatState == 'ChatDone') {
          $('.retract').remove();
          return;
        } else {
          if (retractTimeout <= Settings.chat.msgRetract.retractTimeOut) {
            if ($(this).parent().next()[0].style.display && $(this).parent().next()[0].style.display == 'none') {
              var retractEle = $('.chatContentActive .retract')
              for (var i = 0; i < retractEle.length; i++) {
                retractEle[i].style.display = 'none'
              }
            }
            $(this).parent().next().toggle();// 3.9 聊天显示区滚动轴置底
            if ($(this).parent().next().next().attr('class').indexOf('reminder ') > -1) {
              $(".chat-interaction-scroll .el-scrollbar__wrap")[0].scrollTop = $(".chat-interaction-scroll .el-scrollbar__wrap")[0].scrollHeight;
            }
          } else {
            $(this).parent().next().hide();
          }
        }
      }
    }
  });

  // 撤回消息按钮
  $('.chat-interaction').on('click', '.retract', function () {
    var curUser = Model.people.get_user();
    var retractTime = $(this).prev().attr('retractTime');
    var retractTimeout = Utils.retractTimeDifference(retractTime);
    // 1.当前用户信息处理
    if (curUser && retractTimeout <= Settings.chat.msgRetract.retractTimeOut) {
      // 1.1 撤回消息
      var readid = $(this).prev().attr('readid');
      let msg = {
        msgtype: 'retract',
        content: '撤回',
        readid: readid
      }
      chatUiKit.sendCurrentUsrMsg(msg)
      $(this).hide()
      $(this).prev().remove()
      $(this).after('<span class="retractTitle">你撤回了一条消息</span>')
    } else {
      globalUiKit.notify('', '该条消息发送时间已超过 ' + Settings.chat.msgRetract.retractTimeOut + ' 分钟,无法撤回!');
      $(this).hide();
    }
  });

  // 音频转换为文本
  $('.chat-interaction').on('click', '.chatContentActiveAudioText', function () {
    $(this).css({
      'color': '#3167af',
      'border': '2px solid #3167af'
    })
    $(this).parent().next().show();
  });

  // 机器人直接发送
  this.redirectSendBtnClick = function (sessionId) {
    let user = Model.people.get_by_sid(sessionId)
    if (!user || user.chatState === 'ChatDone') {
      return
    }
    var content = $('.chat-robot[name=' + sessionId + '] p').attr('answer');
    var robotUserData = $('.chat-robot[name=' + sessionId + '] p').attr('robotUserData');
    var showAnswer = $('.chat-robot[name=' + sessionId + '] p').attr('showAnswer');
    let msg = {}
    msg.msgtype = 'text'
    msg.content = content
    msg.agentContent = showAnswer
    msg.sessionId = sessionId
    if (robotUserData) {
      msg.robotUserData = JSON.parse(robotUserData)
    }
    if (Constants.sensitiveFlag == "true") {
      let robot = true
      Sensitive.isIncludeSensitive(function () {
        chatUiKit.sendCurrentUsrMsg(msg)
      }, robot, msg.content)
    } else {
      chatUiKit.sendCurrentUsrMsg(msg)
    }

    $('.chat-robot[name=' + sessionId + ']').hide()
  },

    // 机器人编辑发送
    this.editSendBtnClick = function (sessionId) {
      let user = Model.people.get_by_sid(sessionId)
      if (!user || user.chatState === 'ChatDone') {
        return
      }
      var txtInput = $('.chat-mess.' + sessionId);
      let originalContent = txtInput.val()
      txtInput.val(originalContent + $('.chat-robot[name=' + sessionId + '] p').text())
      txtInput.trigger('focus')
      $('.chat-robot[name=' + sessionId + ']').hide()
    },

    // 机器人编辑关闭
    this.editSendCloseClick = function (sessionId) {
      $('.chat-robot[name=' + sessionId + ']').hide()
    },

    // 获取座席昵称
    this.getAgentNickName = function (sessionId, obj, tip) {
      let messageJson = {}
      messageJson.parentEle = $('.chatcontent[name=' + sessionId + ']')
      messageJson.sessionId = sessionId
      messageJson.mediatype = 'text'
      messageJson.toUser = i18n.promptMessage.chatTips.System
      var partyname = obj.partyname;
      var urlStr = window.CONFIG.restIp + '/v1/customer/agent_info?agentId=' + partyname
      CommonApi.httpGetRequest(urlStr, function (dbResponse) {
        if (dbResponse && dbResponse.data) {
          var data = dbResponse.data;
          if (data) {
            partyname = data.userNickname || obj.partyname;
          }
          messageJson.message = tip.replace('<AgentNickName>', chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + partyname)
          self.appendChatMessageToMe(messageJson)
        } else {
          messageJson.message = tip.replace('<AgentNickName>', chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + partyname)
          self.appendChatMessageToMe(messageJson)
        }
      }, function () {
        messageJson.message = tip.replace('<AgentNickName>', chatUiKit.getAgentNickNamePrefixByAppid(sessionId) + partyname)
        self.appendChatMessageToMe(messageJson)
      })
    }
  //根据appid获取座席昵称前缀 
  this.getAgentNickNamePrefixByAppid = function (sessionId) {
    var user = Model.people.get_by_sid(sessionId);
    if (!user || !user.userData.appid) {
      return "";
    } else {
      var channelParameter = CommonParameters.getChannelParameterByAppid(user.userData.appid);
      return channelParameter.agentNicknamePrefix || "";
    }
  }
}

